<template>
  <div>
    <div class="flex justify-between w-full">
      <h3 style="display: inline-block">
        {{ $t("business.workload.deploy_strategy") }}
      </h3>
      <el-button
        v-if="!uiState.editAble"
        style="margin-left: 10px"
        type="text"
        icon="Edit"
        @click="onHandleEdit"
      >
        {{ $t("commons.button.click_to_edit") }}
      </el-button>
    </div>
    <div v-loading="uiState.loading">
      <el-form ref="form" label-position="top" :model="yamlInfo">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
              :label="$t('business.workload.strategy')"
              prop="spec.strategy.type"
              required
            >
              <span v-if="!uiState.editAble" style="margin-left: 10px">
                {{ getLabels(yamlInfo.spec.strategy.type) }}
              </span>
              <el-select
                v-else
                v-model="yamlInfo.spec.strategy.type"
                style="width: 100%"
                @change="onStrategyTypeChange"
              >
                <el-option
                  v-for="(item, index) in options.deployment_strategy_list"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row
          v-if="yamlInfo.spec.strategy.type === 'RollingUpdate'"
          :gutter="20"
        >
          <el-col :span="12">
            <el-form-item
              :label="$t('business.workload.max_surge')"
              prop="spec.strategy.rollingUpdate.maxSurge"
              :rules="NumberPercentRule"
            >
              <span v-if="!uiState.editAble" style="margin-left: 10px">
                {{ yamlInfo.spec.strategy.rollingUpdate.maxSurge }}
              </span>
              <el-input
                v-else
                v-model="yamlInfo.spec.strategy.rollingUpdate.maxSurge"
              >
                <template #append>
                  <span>%</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              :label="$t('business.workload.max_unavaliable')"
              prop="spec.strategy.rollingUpdate.maxUnavailable"
              :rules="NumberPercentRule"
            >
              <span v-if="!uiState.editAble" style="margin-left: 10px">
                {{ yamlInfo.spec.strategy.rollingUpdate.maxUnavailable }}
              </span>
              <el-input
                v-else
                v-model="yamlInfo.spec.strategy.rollingUpdate.maxUnavailable"
              >
                <template #append>
                  <span>%</span>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="uiState.editAble" style="float: right">
          <el-button @click="updateWorkLoad">
            {{ $t("commons.button.submit") }}
          </el-button>
          <el-button @click="uiState.editAble = false">
            {{ $t("commons.button.cancel") }}
          </el-button>
        </div>
        <br />
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive } from "vue";
import {
  DaemonSet,
  Deployment,
  StatefulSet,
  useK8SApi
} from "../../../api/k8s";
import { useI18n } from "vue-i18n";
import { useFormRule } from "@/views/domain/kubeHud/utils/rules";

// import { updateWorkLoad } from "@/api/workloads";
// import Rule from "@/utils/rules";
const { NumberPercentRule } = useFormRule();

const { deploymentRepo } = useK8SApi();
const { t } = useI18n();

type Prop = {
  cluster: string;
  resourceType: string;
};

const yamlInfo = defineModel<Deployment | any>("yamlInfo");
const props = withDefaults(defineProps<Prop>(), {
  cluster: "",
  resourceType: ""
});

const uiState = reactive({
  loading: false,
  editAble: false,
  numberPercentRule: NumberPercentRule
});

const options = reactive({
  deployment_strategy_list: [
    {
      label: t("business.workload.rolling_update"),
      value: "RollingUpdate"
    },
    { label: t("business.workload.recreate"), value: "Recreate" }
  ],
  strategy_list: [
    {
      label: t("business.workload.rolling_update"),
      value: "RollingUpdate"
    },
    { label: t("commons.button.delete"), value: "OnDelete" }
  ]
});

const onHandleEdit = () => {
  if (yamlInfo.value.spec.strategy.rollingUpdate) {
    yamlInfo.value.spec.strategy.rollingUpdate.maxSurge =
      `${yamlInfo.value.spec.strategy.rollingUpdate.maxSurge}`.replaceAll(
        "%",
        ""
      );

    yamlInfo.value.spec.strategy.rollingUpdate.maxUnavailable =
      `${yamlInfo.value.spec.strategy.rollingUpdate.maxUnavailable}`.replaceAll(
        "%",
        ""
      );
  }

  uiState.editAble = true;
};

const fixRollingUpdateData = () => {
  const rollingUpdate = yamlInfo.value.spec.strategy.rollingUpdate ?? {};
  rollingUpdate.maxSurge = `${parseInt(`${rollingUpdate.maxSurge}`.replaceAll("%", ""))}%`;
  rollingUpdate.maxUnavailable = `${parseInt(`${rollingUpdate.maxUnavailable}`.replaceAll("%", ""))}%`;
  yamlInfo.value.spec.strategy.rollingUpdate = rollingUpdate;
};

const onStrategyTypeChange = (type: string) => {
  if (type === "Recreate") {
    delete yamlInfo.value.spec.strategy.rollingUpdate;
  } else {
    fixRollingUpdateData();
  }
};
const validateStrategyType = () =>
  onStrategyTypeChange(yamlInfo.value.spec.strategy.type);

const updateWorkLoad = async () => {
  validateStrategyType();
  uiState.loading = true;
  deploymentRepo.updateDeployment({}, yamlInfo.value).finally(() => {
    uiState.editAble = false;
    uiState.loading = false;
  });
};

const getLabels = (value: string) => {
  switch (value) {
    case "RollingUpdate":
      return t("business.workload.rolling_update");
    case "Recreate":
      return t("business.workload.recreate");
    case "OnDelete":
      return t("commons.button.delete");
  }
};
</script>

<style scoped></style>
